package org.sjs.dreamfly.biz.news

import androidx.lifecycle.ViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.sjs.dreamfly.app.PlayInfoLoadedEvent
import org.sjs.dreamfly.app.PlayListLoadedEvent
import org.sjs.dreamfly.app.defaultEventBus
import org.sjs.dreamfly.browser.WebLocation
import org.sjs.dreamfly.common.util.LogUtil
import org.sjs.dreamfly.common.util.UriUtils
import org.sjs.dreamfly.model.VideoInfo
import org.sjs.dreamfly.model.toutiao.FeedInfo
import org.sjs.dreamfly.network.ApiConstants
import org.sjs.dreamfly.network.RetrofitUtil
import org.sjs.dreamfly.network.api.TouTiaoApi
import org.sjs.dreamfly.player.IPlayerDataProvider
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception

class NewsViewModel: ViewModel(), IPlayerDataProvider {

    private val videoList = mutableListOf<VideoInfo>()
    private var loadMoreApi: String? = null

    override suspend fun loadVideoList(): MutableList<VideoInfo> {
        LogUtil.d("")
        return videoList
    }

    override fun getVideoList(): MutableList<VideoInfo> {
        return videoList
    }

    override fun loadMore(callback: () -> Unit?) {
        loadMoreApi?.let {
            loadMore(it)
            callback()
        }
    }

    fun onPlayInfoLoaded(event: PlayInfoLoadedEvent): Boolean {
        return addToList(event.videoInfo, 0)
    }

    fun onPlayListLoaded(list: List<VideoInfo>): List<VideoInfo> {
        val added = mutableListOf<VideoInfo>()
        list.forEach {
            LogUtil.d("${it.title}")
            if (addToList(it)) {
                added.add(it)
            }
        }
        return added
    }

    private fun addToList(videoInfo: VideoInfo, index: Int? = null): Boolean {
        val found = videoList.find { isSameVideo(it, videoInfo) }
        if (found == null) {
            if (index != null && index >= 0 && index < videoList.size) {
                videoList.add(index, videoInfo)
            } else {
                videoList.add(videoInfo)
            }
            LogUtil.d("size:${videoList.size} added videoInfo:${videoInfo}")
            return true
        } else {
            if (found.title.isNullOrBlank()) found.title = videoInfo.title
            if (found.imageUrl.isNullOrBlank()) found.imageUrl = videoInfo.imageUrl
        }
        return false
    }

    private fun isSameVideo(a: VideoInfo, b: VideoInfo): Boolean {
        if (a.title == b.title) return true
        val aArray = a.videoUrl?.split("/")
        val bArray = b.videoUrl?.split("/")
        if (aArray == null || bArray == null ||
            aArray.size < 4 || bArray.size < 4 ||
            aArray.size != bArray.size) return false
        for (i in 4 until aArray.size) {
            if (aArray[i] != bArray[i]) return false
        }
        return true
    }

    fun loadMore(url: String) {
        loadMoreApi = url
        LogUtil.d("url:$url")
        MainScope().launch {
            val baseURL = ApiConstants.BASE_URL_TOUTIAO
            val queryMap = UriUtils.extractQueryParams(loadMoreApi!!)
//            https://m.toutiao.com/related/open/7230694415335948852/?
            val id = loadMoreApi!!.split("/?")[0].replace("https://m.toutiao.com/related/open/", "")
            val feedInfo = withContext(Dispatchers.IO) {
                var result: FeedInfo? = null
                try {
                    val response = RetrofitUtil.getTouTiaoRetrofit().create(TouTiaoApi::class.java)
                        .loadRecommendVideo(
                            id = id,
                            parentRid = queryMap["parent_rid"],
                            codeId = queryMap["code_id"],
                            recommendRid = queryMap["recommend_rid"],
                            siteId = queryMap["site_id"]
                        )?.execute()
                    LogUtil.d("loadMore size: ${response?.body()?.data?.size} ${response?.body()}")
                    result = response?.body()

                } catch (e: Exception) {
                    e.printStackTrace()
                }
                return@withContext result
            }
            val list = mutableListOf<VideoInfo>()
            feedInfo?.data?.let {
                it.forEach { item->
                    item?.let { i->
                        if (i.feed_type == 8) {
                            list.add(i.toVideoInfo())
                        }
                    }
                }
            }
            if (list.isNotEmpty()) {
                defaultEventBus.post(PlayListLoadedEvent(WebLocation(href = url), list))
            }
        }
    }
}